package com.hengxinguotong.zhihuichengjian.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.net.Downloader;
import com.hengxinguotong.zhihuichengjian.utils.CommUtil;
import com.hengxinguotong.zhihuichengjian.utils.ToastUtils;

import java.io.File;

import butterknife.BindView;
import butterknife.ButterKnife;


/**
 * TODO
 *
 * @author hjz
 * @version V1.0.0
 * @since 2019/4/19 10:06
 */

public class AppUpgradeDialog extends AlertDialog
{
    private static final String TAG = "AppUpgradeDialog";

    @BindView(R.id.mProgressBar)
    ProgressBar mProgressBar;
    @BindView(R.id.upgrade_percent)
    TextView upgradePercent;
    @BindView(R.id.upgrade_max)
    TextView upgradeMax;
    @BindView(R.id.upgrade_complete)
    TextView upgradeComplete;

    private Context context;
    private String remotePath;
    private String localPath;

    public AppUpgradeDialog(Context context)
    {
        super(context, android.R.style.Theme_DeviceDefault_Light_Dialog);
        this.context = context;
    }

    protected AppUpgradeDialog(Context context, boolean cancelable, OnCancelListener cancelListener)
    {
        super(context, cancelable, cancelListener);
    }

    protected AppUpgradeDialog(Context context, int themeResId)
    {
        super(context, themeResId);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dialog_app_upgrade);
        ButterKnife.bind(this);
        setCancelable(false);
        setCanceledOnTouchOutside(false);

        new Downloader.Builder(context)
                .remoteUrl(remotePath)
                .localUrl(localPath)
                .threadCount(3)
                .callback(getOnDownload())
                .build().download();
    }

    private Downloader.OnDownload getOnDownload()
    {
        return new Downloader.OnDownload()
        {
            @Override
            public void onStart(long fileSize, long complete)
            {
                mProgressBar.setMax((int) fileSize);
                mProgressBar.setProgress((int) complete);
                upgradeMax.setText(context.getString(R.string.upgrade_max, fileSize / 1024));
                upgradeComplete.setText(String.valueOf(complete / 1024));
                upgradePercent.setText(context.getString(R.string.upgrade_percent, complete * 100 / fileSize));
            }

            @Override
            public void onProgress(long complete)
            {
                mProgressBar.setProgress((int) complete);
                upgradeComplete.setText(String.valueOf(complete / 1024));
                upgradePercent.setText(context.getString(R.string.upgrade_percent, complete * 100 / mProgressBar.getMax()));
            }

            @Override
            public void onThreadEnd(int threadId)
            {
                Log.e(TAG, "Thread " + threadId + "End");
            }

            @Override
            public void onThreadError(int threadId, String error)
            {
                Log.e(TAG, "Thread " + threadId + error);
            }

            @Override
            public void onEnd()
            {
                dismiss();
                installApk(new File(localPath));
            }

            @Override
            public void onError()
            {
                dismiss();
                ToastUtils.showSimpleToast(context, R.string.upgrade_download_fail);
            }
        };
    }

    public void setDownloadPath(String path)
    {
        this.remotePath = path;
        File loadFile = new File(CommUtil.getDataDir(context, "apk"), "ZHCJ.apk");
        if (!loadFile.getParentFile().exists())
        {
            loadFile.getParentFile().mkdirs();
        }
        this.localPath = loadFile.getAbsolutePath();
    }

    private void installApk(File file)
    {
        if (file == null || !file.exists()) return;
        Intent intent = new Intent();
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Intent.ACTION_VIEW);
        String type = "application/vnd.android.package-archive";
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N)
        {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            String authority = "com.hengxinguotong.zhihuigongdi.provider_paths";
            Uri contentUri = FileProvider.getUriForFile(context, authority, file);
            intent.setDataAndType(contentUri, type);
        } else
        {
            intent.setDataAndType(Uri.fromFile(file), type);
        }
        context.startActivity(intent);
    }
}
